import {BASE_URL} from "@/config/base";

/**
 * 全局跳转
 * @param url 跳转的页面地址
 * @returns
 */
export const navTo = (url) => {
    if (url.indexOf("/pages/") != -1 || url.indexOf("/subPackage/") != -1) {
        uni.navigateTo({
            url: url,
        });
    } else if (url == "back") {
        uni.navigateBack();
    }
};

/**
 * 防抖函数
 * @param fn 需要执行的函数
 * @param time 间隔时间
 * @returns
 */
export const debounce = (func, wait, immediate) => {
    let timeout; // 定义一个计时器变量，用于延迟执行函数
    return function (...args) {
        // 返回一个包装后的函数
        const context = this; // 保存函数执行上下文对象
        const later = function () {
            // 定义延迟执行的函数
            timeout = null; // 清空计时器变量
            if (!immediate) func.apply(context, args); // 若非立即执行，则调用待防抖函数
        };
        const callNow = immediate && !timeout; // 是否立即调用函数的条件
        clearTimeout(timeout); // 清空计时器
        timeout = setTimeout(later, wait); // 创建新的计时器，延迟执行函数
        if (callNow) func.apply(context, args); // 如果满足立即调用条件，则立即执行函数
    };
};

/**
 * 节流函数
 * @param fn 需要执行的函数
 * @param time 间隔时间
 * @returns
 */
export const throttle = (func, wait) => {
    let timeout; // 定义一个计时器变量，用于限制函数调用频率
    return function (...args) {
        // 返回一个包装后的函数
        const context = this; // 保存函数执行上下文对象
        if (!timeout) {
            // 如果计时器不存在
            func.apply(context, args); // 执行函数
            timeout = setTimeout(() => {
                timeout = null; // 清空计时器变量
            }, wait); // 创建计时器，在指定时间后重置计时器变量
        }
    };
};

// 计算title高度与微信小程序胶囊对齐
export const getTitleTop = () => {
    const sBarHeight = uni.getSystemInfoSync().statusBarHeight;
    let titleTop = 0;
    const menu = uni.getMenuButtonBoundingClientRect();
    titleTop = menu.top + (menu.height - sBarHeight) / 2; //顶部标题对齐
    uni.setStorageSync("systemInfo", {sBarHeight, titleTop});
};

/**
 * 获取屏幕剩余高度
 * @param alreadyheight 手机状态栏高度
 * @returns newsPanelHeight 屏幕剩余高度
 */
export const getScreenSHeight = (alreadyheight) => {
    return new Promise((reslove, reject) => {
        uni.getSystemInfo({
            success: function (res) {
                let newsPanelHeight = res.windowHeight - alreadyheight;
                reslove(newsPanelHeight);
            },
        });
    });
};

/**
 * 获取页面距离顶部高度设置nav颜色
 * @param element 元素类名
 * @returns bgColor navBar背景颜色
 */
export const setNavBgColor = (element) => {
    return new Promise((resolve, reject) => {
        let view = uni.createSelectorQuery().select(element);
        let {sBarHeight, titleTop} = uni.getStorageSync("systemInfo");
        let top = sBarHeight + titleTop;
        let bgColor = "";
        view
            .boundingClientRect((data) => {
                if (data.top <= top) bgColor = "#b4e4e7";
                if (data.top >= top) bgColor = "transparent";
                resolve(bgColor);
            })
            .exec();
    });
};

/**
 * 获取元素高度
 * @param element 元素类名
 * @returns height 元素高度
 */

export const getElementHeight = (element) => {
    return new Promise((resolve, reject) => {
        let view = uni.createSelectorQuery().select(element);
        view
            .boundingClientRect((data) => {
                const {height} = data;
                resolve(height);
            })
            .exec();
    });
};

/**
 * 获取微信小程序胶囊信息
 */
export const getWXStatusHeight = () => {
    // 获取距上
    const barTop = uni.getSystemInfoSync().statusBarHeight;
    // 获取胶囊按钮位置信息
    const menuButtonInfo = uni.getMenuButtonBoundingClientRect();
    // 获取导航栏高度
    const barHeight = menuButtonInfo.height + (menuButtonInfo.top - barTop) * 2;
    let barWidth = menuButtonInfo.width;
    uni.setStorageSync("capsule", {barTop, barHeight, barWidth});
};

/**
 * 上传图片多张
 * @param count 上传数量
 * @param sourceType 类型
 * @returns resultObj 返回图片信息
 */
let queue = [];
let urlList = [];
export const uploadImage = (count = 1, item = '', imgList=[]) => {
    return new Promise((reslove, reject) => {
        if(item) {
            let index = urlList.findIndex(data => data == item)
            urlList.splice(index, 1)
            queue.splice(index, 1)
            return false
        }
        if(imgList.length) {
            urlList = [ ...imgList, ...urlList]
        }
        uni.chooseImage({
            count: count,
            sizeType: ["original", "compressed"], //可以指定是原图还是压缩图，默认二者都有
            sourceType: ["camera", "album"], //从相册选择
            success: async (res) => {
                await uni.showLoading({
                    title: "上传中",
                });
                let fileList = res.tempFilePaths;
                fileList.forEach((item) => {
                    queue.push(upload(item));
                });
                const listRes = await Promise.all(queue);
                listRes.forEach((item) => {
                    urlList.push(item[0])
                });
                urlList = Array.from(new Set(urlList))
                reslove(urlList);
                urlList = []
                imgList = []
                queue = []
            },
        });
    });
};

const upload = (item) => {
    return new Promise((reslove, reject) => {
        let urlList = [];
        uni.uploadFile({
            url: BASE_URL + "/prod-api/common/upload",
			 // url: BASE_URL + "/common/upload",
            header: {
                "content-type": "multipart/form-data",
                Authorization: "Bearer " + uni.getStorageSync("token"),
            },
            filePath: item,
            name: "file",
            success: (result) => {
                let resultObj = JSON.parse(result.data);
                urlList = [...urlList, resultObj.url];
                reslove(urlList);
                uni.hideLoading();
            },
            fail: (err) => {
                uni.hideLoading()
                uni.showToast({
                    title: "上传失败",
                    icon: "none",
                });
                reject(err);
            },
        });
    });
};

/**
 * 上传文件
 *
 */
export const uploadFile = () => {
    return new Promise((reslove, reject) => {
        uni.chooseMessageFile({
            // 只能选取微信聊天框中的文件
            count: 1, // 最多选择一个文件
            type: "file", // 选择文件类型
            success: function (res) {
                // 获取文件的本地临时文件路径
                const tempFiles = res.tempFiles[0];
                uni.showLoading({
                    title: "正在上传",
                });
                uni.uploadFile({
                    url: BASE_URL + "/index.php/api/upload/temporary", //服务器地址
                    filePath: tempFiles.path, //文件临时路径
                    name: "file",
                    header: {
                        "Content-Type": "multipart/form-data",
                    },
                    formData: {
                        type: "document",
                    },
                    success: (res) => {
                        reslove(JSON.parse(res.data).data);
                        // 上传成功执行
                        uni.hideLoading();
                    },
                    fail: (error) => {
                        reject(error);
                        uni.hideLoading();
                    },
                });
            },
        });
    });
};

//点击保存到相册
// base64
export const saveImage = (imgUrl) => {
    uni.showLoading({
        title: "保存中",
    });
    var byte = imgUrl.replace("data:image/png;base64,", "");
    const fs = uni.getFileSystemManager(); //全局唯一的文件管理器
    console.log(byte, "by");
    var number = Math.random();
    fs.writeFile({
        filePath: wx.env.USER_DATA_PATH + "/code" + number + ".png",
        data: byte,
        encoding: "base64",
        success(res) {
            uni.saveImageToPhotosAlbum({
                //保存为png格式到相册
                filePath: wx.env.USER_DATA_PATH + "/code" + number + ".png",
                success: function (res) {
                    uni.showToast({title: "下载成功", icon: "none"});
                    uni.hideLoading();
                },
                fail: function (err) {
                    console.log(err);
                    uni.hideLoading();
                },
            });
        },
    });
};

// 保存图片 url
//下载海报，只在APP内有效
export const downPicture = (url) => {
    uni.showLoading({
        title: "保存中",
    });
    uni.downloadFile({
        //下载
        url: url, //图片下载地址
        success: (res) => {
            if (res.statusCode === 200) {
                uni.saveImageToPhotosAlbum({
                    //保存图片到系统相册。
                    filePath: res.tempFilePath, //图片文件路径
                    success: function () {
                        uni.showToast({
                            title: "图片保存成功",
                            icon: "none",
                        });
                        uni.hideLoading();
                    },
                    fail: function (e) {
                        console.log(e);
                        uni.showToast({
                            title: "图片保存失败",
                            icon: "none",
                        });
                        uni.hideLoading();
                    },
                });
            }
        },
    });
};

// 上传单张图片
export const dUpload = () => {
    return new Promise((reslove, reject) => {
        uni.chooseImage({
            //选择图片
            count: 1, //图片数量默认9
            sizeType: ["compressed"], //可以指定是原图还是压缩图，默认二者都有
            sourceType: ["camera", "album"], //album 从相册选图，camera 使用相机，默认二者都有。如需直接开相机或直接选相册，请只使用一个选项
            success: (res) => {
                uni.showLoading({
                    title: "上传中",
                });
                var tempFilePaths = res.tempFilePaths;
                uni.uploadFile({
                    //上传图片至服务器
                    url: BASE_URL + "/prod-api/common/upload",
                    filePath: tempFilePaths[0],
                    name: "file",
                    header: {
                        "content-type": "multipart/form-data",
                        Authorization: "Bearer " + uni.getStorageSync("token"),
                    },
                    success: (uploadFileRes) => {
                        console.log(uploadFileRes, "uploadFileRes");
                        if (uploadFileRes.statusCode == 200) {
                            let file = JSON.parse(uploadFileRes.data);
                            uni.hideLoading();
                            uni.showToast({
                                title: "上传成功",
                                icon: "none",
                            });
                            reslove(file.url);
                        }
                    },
                });
            },
            fail: (err) => {
                uni.hideLoading();
                uni.showToast({
                    title: "上传失败",
                    icon: "none",
                });
            },
        });
    });
};

// 时间格式化
export const dateFormat = (dateStr) => {
    // 时间戳（以毫秒为单位）
    // 创建一个 Date 对象
    const date = new Date(dateStr);
    // 提取日期和时间组件
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, "0");
    const day = String(date.getDate()).padStart(2, "0");
    const hours = String(date.getHours()).padStart(2, "0");
    const minutes = String(date.getMinutes()).padStart(2, "0");
    const seconds = String(date.getSeconds()).padStart(2, "0");
    // 格式化为 YYYY-MM-DD HH:MM:SS
    const formattedDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    return formattedDate;
};


// 去除空对象字段
export const deleteObjectEmptyKey = (object) => {
    return Object.fromEntries(
        Object.entries(object).filter(([key, value]) => value !== null && value !== undefined && value !== "")
    );
}

// 支付
export const wxPayment = (data, path) => {
    return new Promise((resolve, reject) => {
        const {appId, nonceStr, packageVal, paySign, signType, timeStamp} = data
        uni.requestPayment({
            provider: 'wxpay',
            timeStamp,
            nonceStr,
            package: packageVal,
            signType,
            paySign,
            success: async (res) => {
                if (res.errMsg === 'requestPayment:ok') {
                    uni.hideLoading()
                    await uni.requestSubscribeMessage({
                        tmplIds: ['lRAXdz_pHzHq9RRLreThlPSyV20ikgLYNqwMVc27eKY'],
                        success: async res => {
                            console.log(res, 'res')
                            if (path) {
                                await uni.showToast({
                                    title: '支付成功',
                                    icon: 'none'
                                })

                                    await uni.reLaunch({
                                        url: path
                                    })
                            } else {
                                uni.hideLoading()
                                await uni.showToast({
                                    title: '发布成功,待审核',
                                    icon: 'none'
                                })
                                resolve('ok')
                                setTimeout(() => {
                                    uni.navigateBack()
                                }, 1500)
                            }
                        },
                        fail: err => {
                            console.log(err, 'err')
                        }
                    })

                }
            },
            fail: async (err) => {
                uni.hideLoading()
                await uni.showToast({
                    title: '您取消了支付',
                    icon: 'none'
                })
            }
        })
    })
}

// 复制
export const copy = (value) => {
    uni.setClipboardData({
        data: value,
        success: async function () {
            await uni.showToast({
                title: '复制成功',
                icon: 'none'
            })
        }
    })
}

// 图片预览
export const imagePriview = (imageUrlList, index) => {
    uni.previewImage({
        urls: imageUrlList,
        current: index
    })
}
